/**
 * Copyright 2018
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.service.impl;

import io.renren.common.utils.RedisUtils;
import io.renren.dao.SysConfigDao;
import io.renren.entity.SysConfigEntity;
import io.renren.service.SysConfigService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;

@Service("sysConfigService")
public class SysConfigServiceImpl extends ServiceImpl<SysConfigDao, SysConfigEntity> implements SysConfigService {

	@Autowired
	RedisUtils redisUtils;

	private void saveOrUpdate(SysConfigEntity config) {
		if (config == null) {
			return;
		}
		redisUtils.set("sys:config:" + config.getKey(), config);
	}

	private SysConfigEntity get(String key) {
		return redisUtils.get("sys:config:" + key, SysConfigEntity.class);
	}

	@Override
	public String getValue(String key) {
		SysConfigEntity config = get(key);
		if (config == null) {
			config = baseMapper.queryByKey(key);
			saveOrUpdate(config);
		}

		return config == null ? null : config.getValue();
	}

	@Override
	public int getValueI(String key) {
		return Integer.parseInt(getValue(key));
	}

	@Override
	public long getValueL(String key) {
		return Long.parseLong(getValue(key));
	}

	@Override
	public double getValueD(String key) {
		return Double.parseDouble(getValue(key));
	}
}
